/* eslint-disable no-negated-condition */
import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {Button, Form, Row, Col, Card, Spin, Table, message as msg} from 'antd';
import {getDetail} from './api';
import {FORM_OPTIONS, TABLE, DATE_FORMAT} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import FileUpload from './FileUpload';
import SalePackingListPanel from './SalePackingListPanel';
import {currency, packingType, packingListType} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {
            totalAmount: 0
        },
        showSalePackingListPanel: false,
    };

    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data,
                            details: res.data.details
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onClickAddBtn = () => {
        if(!this.state.data.dealerId)
            msg.warn(this.props.intl.formatMessage({
                id: 'NewPanel.message.choseDealer',
                defaultMessage: '请先选择总代'
            }));
        if(this.state.data.dealerId)
            this.setState({showSalePackingListPanel: true});
    }
    onCloseSalePackingListPanel = () => {
        this.setState({showSalePackingListPanel: false});
    }
    onSelectAddedSalePackingList = records => {
        const retailDetails = this.state.details || [];
        records.forEach(r => {
            const index = retailDetails.findIndex(v => v.id === r.id);
            if(index === -1)
                retailDetails.push({
                    id: r.id,
                    code: r.code,
                    dealerCode: r.dealerCode,
                    dealerName: r.dealerName,
                    saleConfirmationrCode: r.saleConfirmationrCode,
                    batchNumber: r.batchNumber,
                    status: r.status,
                    packingType: r.packingType,
                    container: r.container,
                    length: r.length,
                    width: r.width,
                    height: r.height,
                    volume: r.volume,
                    netWeight: r.netWeight,
                    grossWeight: r.grossWeight,
                    currency: r.currency,
                    createTime: r.createTime,
                    totalAmount: r.totalAmount
                });
        });
        this.setState({
            details: [...retailDetails],
            hasOperat: true,
            showSalePackingListPanel: false
        });
    }
    onSubmit = () => {
        let oneBrand = undefined;
        if(this.props.initEnum.brands.length === 1)
            oneBrand = true;
        const isValid = newOrUpdateOrderValidator(this.state.data, this.state.details, oneBrand);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        if(!this.state.data.brandId && this.props.initEnum.brands.length === 1)
            // eslint-disable-next-line react/no-direct-mutation-state
            this.state.data.brandId = this.props.initEnum.brands[0].value;
        this.props.onSubmit(this.state.data, this.state.details).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    
    onSelectDealer = (condition = {}) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                }
            };
        });
    };
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    render() {
        const {data, details} = this.state;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateCode = !data.code && this.state.validate ? 'error' : null;
        const validateCurrency = !data.currency && this.state.validate ? 'error' : null;
        const validateTotalAmount = !data.totalAmount && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const submitable = hasPermissions(PERMISSIONS.add, pagePermission);
        let amont = 0;
        if(details && details.length !== 0) {
            data.currency = details[0].currency;
            details.forEach(v => {
                amont += v.totalAmount;
                data.totalAmount = amont;
            });
        }
        const columns = [{
            title: formatMessage({
                id: 'newPanel.column.code',
                defaultMessage: '包装箱单号'
            }),
            dataIndex: 'code',
        }, {
            title: formatMessage({
                id: 'newPanel.column.dealerCode',
                defaultMessage: '总代编号'
            }),
            dataIndex: 'dealerCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.dealerName',
                defaultMessage: '总代名称'
            }),
            dataIndex: 'dealerName',
        }, {
            title: formatMessage({
                id: 'newPanel.column.saleConfirmationrCode',
                defaultMessage: '销售确认书编号'
            }),
            dataIndex: 'saleConfirmationrCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.batchNumber',
                defaultMessage: '批次号'
            }),
            dataIndex: 'batchNumber',
        }, {
            title: formatMessage({
                id: 'newPanel.column.packingType',
                defaultMessage: '包装类型'
            }),
            dataIndex: 'packingType',
            render: text => conventEnumValueToString(packingType, text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.container',
                defaultMessage: '包装规格'
            }),
            dataIndex: 'container',
        }, {
            title: formatMessage({
                id: 'newPanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(packingListType, text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.length',
                defaultMessage: '长度(mm)'
            }),
            dataIndex: 'length',
        }, {
            title: formatMessage({
                id: 'newPanel.column.width',
                defaultMessage: '宽度(mm)'
            }),
            dataIndex: 'width',
        }, {
            title: formatMessage({
                id: 'newPanel.column.height',
                defaultMessage: '高度(mm)'
            }),
            dataIndex: 'height',
        }, {
            title: formatMessage({
                id: 'newPanel.column.volume',
                defaultMessage: '体积(m³)'
            }),
            dataIndex: 'volume',
        }, {
            title: formatMessage({
                id: 'newPanel.column.netWeight',
                defaultMessage: '净重(kg)'
            }),
            dataIndex: 'netWeight',
        }, {
            title: formatMessage({
                id: 'newPanel.column.grossWeight',
                defaultMessage: '毛重(kg)'
            }),
            dataIndex: 'grossWeight',
        }, {
            title: formatMessage({
                id: 'newPanel.column.totalAmount',
                defaultMessage: '总金额'
            }),
            dataIndex: 'totalAmount',
        }, {
            title: formatMessage({
                id: 'newPanel.column.createTime',
                defaultMessage: '导入时间'
            }),
            dataIndex: 'createTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.code',
                                            defaultMessage: '发票号'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateCode} required>
                                        <TextInput
                                            name="code"
                                            value={data.code}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required>
                                        {this.props.initEnum.brands.length !== 1 ? <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={this.props.initEnum.brands}
                                            onChange={this.handleFilterChange}/>
                                            : this.props.initEnum.brands[0].text}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                        {!this.props.id ? <DealerSelectPanel
                                            value={dealerInfo}
                                            onChange={this.handleFilterChange}
                                            onSelect={this.onSelectDealer} />
                                            : `(${data.dealerCode})${data.dealerName}`
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.currency',
                                            defaultMessage: '币种'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateCurrency} required>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.totalAmount',
                                            defaultMessage: '总金额'
                                        })} {...FORM_OPTIONS.item} validateStatus={validateTotalAmount} required>
                                        {formatAmount(data.totalAmount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.remark',
                                            defaultMessage: '备注'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={<Row>
                                <Col {...FORM_OPTIONS.col}>
                                    {this.props.intl.formatMessage({
                                        id: 'newPanel.details',
                                        defaultMessage: '清单'
                                    })}
                                </Col>
                                
                            </Row>}
                            extra={<div>
                                <Button
                                    size="small"
                                    onClick={this.onClickAddBtn}>
                                    {formatMessage({
                                        id: 'newPanel.operation.newDetail',
                                        defaultMessage: '新增清单'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Card>
                        <Card title={formatMessage({
                            id: 'newPanel.title.files',
                            defaultMessage: '附件清单'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload}
                                        onRemove={this.removeFilePath}
                                        fileList={data.attachments || []}/>
                                </Col>
                            </Row>
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
                {
                    this.state.showSalePackingListPanel &&
                        <SalePackingListPanel
                            selectKey={data.id}
                            dealerId={data.dealerId}
                            brandId={this.props.initEnum.brands.length !== 1 ? data.brandId : this.props.initEnum.brands[0].value}
                            onCancel={this.onCloseSalePackingListPanel}
                            onSelect={this.onSelectAddedSalePackingList} />
                }
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `${'('}${item.code}${')'}${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: (data, details) => dispatch(onSubmit(data, details)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
